package demo2;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-09-06
 * Time: 19:28
 */
public class MyList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;

    //尾插法
    public void addLast(int key) {
        ListNode node = new ListNode(key);
        if(head == null) {
            head = node;
            return;
        }
        ListNode newHead = head;
        while(newHead != null) {
            if(newHead.next == null) {
                newHead.next = node;
                return;
            }
            newHead = newHead.next;
        }
    }
    //打印链表
    public void display() {
        ListNode node = head;
        while(node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }
    public void createList() {
        ListNode node1 = new ListNode(11);
        ListNode node2 = new ListNode(22);
        ListNode node3 = new ListNode(33);
        ListNode node4 = new ListNode(44);
        head = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
    }
    //链表逆序(递归)
    public void printList(ListNode node) {
        if(node != null) {
            printList(node.next);
            System.out.println(node.val);
        }
    }
    //链表逆序(循环)
    public void printList1(ListNode node) {
        if(node == null) {
            return;
        }
        Stack<Integer> stack = new Stack<>();
        while(node != null) {
            stack.add(node.val);
            node = node.next;
        }
        while(!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
    }

    public static void main(String[] args) {
        MyList myList = new MyList();
        myList.createList();
        myList.printList1(myList.head);
    }

}
